<?php

namespace common\models;

use Yii;

/**
 * This is the model class for table "goods".
 *
 * @property int $id 商品id
 * @property string $goods_no 商品编号
 * @property string $name 商品名称
 * @property string $nums 库存数量
 * @property int $seller_id 商家ID
 * @property string $seller 商家名称
 * @property string $price 价格
 * @property string $install_price 安装维护费
 * @property int $status 0:未支付发布费，1:已支付发布费
 * @property int $region_1 商品所在位置区域id
 * @property int $region_2 二级地域
 * @property int $region_3 三级地域
 * @property string $longitude 经度
 * @property string $latitude 纬度
 * @property string $area_num 广告位规格
 * @property int $first_cate 第一级分类
 * @property int $second_cate 第二级分类
 * @property int $third_cate 三级分类
 * @property int $have_package 0:不含套餐，1:含套餐
 * @property int $sort 排序值
 * @property int $order_endtime 订单到期时间
 * @property int $is_auction 是否是拍卖商品
 * @property int $is_tall 0:低空1:高空
 * @property int $auction_begin 拍卖开始时间
 * @property int $auction_end 拍卖结束时间
 * @property int $overtime 到期时间
 * @property int $addtime 添加时间
 */
class Goods extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'goods';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['goods_no', 'seller_id', 'seller', 'price', 'order_endtime', 'overtime', 'addtime'], 'required'],
            [['goods_no', 'seller_id', 'region_1', 'region_2', 'region_3', 'first_cate', 'second_cate', 'third_cate', 'sort', 'order_endtime', 'auction_begin', 'auction_end', 'overtime', 'addtime'], 'integer'],
            [['price', 'longitude', 'latitude'], 'number'],
            [['status'], 'safe'],
            [['name'], 'string', 'max' => 150],
            [['seller'], 'string', 'max' => 100],
            [['status'], 'string', 'max' => 2],
            [['goods_no'], 'unique'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => '商品id',
            'goods_no' => '商品编号',
            'name' => '商品名称',
            'seller_id' => '商家ID',
            'seller' => '商家名称',
            'price' => '价格',
            'status' => '0:未支付发布费，1:已支付发布费',
            'region_1' => '商品所在位置区域id',
            'region_2' => '二级地域',
            'region_3' => '三级地域',
            'longitude' => '经度',
            'latitude' => '纬度',
            'area_num' => '广告位规格',
            'first_cate' => '第一级分类',
            'second_cate' => '第二级分类',
            'third_cate' => '三级分类',
            'have_package' => '0:不含套餐，1:含套餐',
            'sort' => '排序值',
            'order_endtime' => '订单到期时间',
            'is_auction' => '是否是拍卖商品',
            'is_tall' => '0:低空1:高空',
            'auction_begin' => '拍卖开始时间',
            'auction_end' => '拍卖结束时间',
            'overtime' => '到期时间',
            'addtime' => '添加时间',
        ];
    }
    
    public static function goodsSaveCheck(){
        $first_cate = Tools::GetSafeParam('first_cate', 0, 0);
        $second_cate = Tools::GetSafeParam('second_cate', 0, 0);
        $third_cate = Tools::GetSafeParam('third_cate', 0, 0);
        $goodsname = Tools::GetSafeParam('goodsname', "", 1);
        $area_num = Tools::GetSafeParam('area_num', '', 1);
        $price = Tools::GetSafeParam('price', '', 1);
        $install_price = Tools::GetSafeParam('install_price', '', 1);
        $have_package = Tools::GetSafeParam('have_package', 0, 0);
        $package = Tools::GetSafeParam('package', '', 1);
        $order_endtime = Tools::GetSafeParam('order_endtime', "", 1);
        $introduction = Tools::GetSafeParam('introduction', "", 1);
        $longitude = Tools::GetSafeParam('longitude', "0", 1);
        $latitude = Tools::GetSafeParam('latitude', "0", 1);
        $address = Tools::GetSafeParam('address', "", 1);
        $region_area = Tools::GetSafeParam('region_area', "0", 1);
        
        if($first_cate == 0){
            $output['success'] = 0;
            $output['msg'] = '请选择【一级分类】！';
            Tools::outputjson($output);
        }
        if($second_cate == 0){
            $output['success'] = 0;
            $output['msg'] = '请选择【二级分类】！';
            Tools::outputjson($output);
        }
        if($third_cate == 0){
            $output['success'] = 0;
            $output['msg'] = '请选择【三级分类】！';
            Tools::outputjson($output);
        }
        if($goodsname == ''){
            $output['success'] = 0;
            $output['msg'] = '请输入【商品名称】！';
            Tools::outputjson($output);
        }
        if($area_num == '' && $first_cate == 1){
            $output['success'] = 0;
            $output['msg'] = '请输入【广告位规格】！';
            Tools::outputjson($output);
        }
        if($price == ''){
            $output['success'] = 0;
            $output['msg'] = '请选输入【商品价格】！';
            Tools::outputjson($output);
        }
        if(!is_numeric($price)){
            $output['success'] = 0;
            $output['msg'] = '【商品价格】必须是阿拉伯数字！';
            Tools::outputjson($output);
        }
        if(!is_numeric($install_price) && $first_cate == 1){
            $output['success'] = 0;
            $output['msg'] = '【安装维护费】必须是阿拉伯数字！';
            Tools::outputjson($output);
        }
        if($first_cate != 1){
            $install_price = 0;
        }
        
        if($order_endtime == "" && $first_cate == 1 && $have_package==1){
            $output['success'] = 0;
            $output['msg'] = '请选择【起售时间】！';
            Tools::outputjson($output);
        }
        
        if($have_package == 1 && $package==""){
            $output['success'] = 0;
            $output['msg'] = '请填入【套餐信息】！';
            Tools::outputjson($output);
        }
        
        if($first_cate != 1 && $introduction == ''){
            $output['success'] = 0;
            $output['msg'] = '请编辑【商品介绍】！';
            Tools::outputjson($output);
        }
        
        
        //商品图片数据获取：$goodsimg
        $goodsimg = [];
        $goodsimg_nums = 0;
        for($i=0;$i<6;$i++){
            $imgurl = Tools::GetSafeParam('goodsimg_'.$i, "", 1);
            if($imgurl != ""){
                $goodsimg_nums++;
                array_push($goodsimg,$imgurl);
            }
        }
        if($goodsimg_nums == 0){
            $output['success'] = 0;
            $output['msg'] = '需至少上传一张【商品图片】！';
            Tools::outputjson($output);
        }
        
        //根据类型检测商品属性是否正确，合并商品属性与属性值：$goods_attr
        $goods_attr = [];
        $cate_attr = CateAttr::getAttrlistByCate($third_cate);
        foreach($cate_attr as $attr){
            $input_name = 'attr_'.$attr['id'];
            
            if($attr['type']==0){
                $attr_val = Tools::GetSafeParam($input_name, '', 1);
                if($attr['is_must'] == 1 && $attr_val == ""){
                    $output['success'] = 0;
                    $output['msg'] = '请输入【'.$attr['name']."】";
                    Tools::outputjson($output);
                    
                }
                array_push($goods_attr,['name'=>$attr['name'],'attr_id'=>$attr['id'],'attr_val'=>'','sort'=>$attr['sort'],'val'=>$attr_val]);
            }
            if($attr['type']==1){
                $attr_val = Tools::GetSafeParam($input_name, 0, 0);
                $attr_arr = CateAttrVal::getCateAttrArrByAttrId($attr['id']);
                if($attr['is_must'] == 1 && $attr_val == ""){
                    $output['success'] = 0;
                    $output['msg'] = '请选择【'.$attr['name']."】";
                    Tools::outputjson($output);
                }
                array_push($goods_attr,['name'=>$attr['name'],'attr_id'=>$attr['id'],'attr_val'=>$attr_val,'sort'=>$attr['sort'],'val'=>$attr_arr[$attr_val]]);
            }
            if($attr['type']==2){
                $attr_val_arr = [];
                $attr_val = Tools::GetSafeParam($input_name, "", 1);
                if(strlen($attr_val)>2){
                    $attr_val_arr = explode(',', $attr_val);
                }else{
                    $attr_val_arr = [$attr_val];
                }
                $attr_arr = CateAttrVal::getCateAttrArrByAttrId($attr['id']);
                $val_arr = [];
                foreach($attr_val_arr as $val){
                    array_push($val_arr,$attr_arr[$val]);
                }
                $attr_string = implode(',', $val_arr);
                if($attr['is_must'] == 1 && $attr_string == ""){
                    $output['success'] = 0;
                    $output['msg'] = '请至少选择一个【'.$attr['name']."】";
                    Tools::outputjson($output);
                }
                array_push($goods_attr,['name'=>$attr['name'],'attr_id'=>$attr['id'],'attr_val'=>$attr_val,'sort'=>$attr['sort'],'val'=>$attr_string]);
            }
        }
        
        $data = [];
        
        $data['goodsname'] = $goodsname;
        $data['price'] = $price;
        $data['install_price'] = $install_price;
        $data['first_cate'] = $first_cate;
        $data['second_cate'] = $second_cate;
        $data['third_cate'] = $third_cate;
        $data['have_package'] = $have_package;
        if($have_package == 1){
            $data['package'] = $package;
        }
        $data['order_endtime'] = $order_endtime;
        $data['area_num'] = $area_num;
        $data['longitude'] = $longitude;
        $data['latitude'] = $latitude;
        $data['address'] = $address;
        $data['region_area'] = $region_area;
        
        
        
        $data['introduction'] = $introduction;
        $data['goodsimg'] = $goodsimg;
        $data['goods_attr'] = $goods_attr;
        
        return $data;
    }
    
    public static function goodsSave($user,$data){
        $goodsNo = Tools::build_goods_no($user['userid']);
        $goodsModel = new Goods();
        $goodsModel->goods_no = $goodsNo;
        $goodsModel->seller_id = $user['userid'];
        $goodsModel->seller = $user['username'];
        $goodsModel->name = $data['goodsname'];
        $goodsModel->first_cate = $data['first_cate'];
        $goodsModel->second_cate = $data['second_cate'];
        $goodsModel->third_cate = $data['third_cate'];
        $goodsModel->have_package = $data['have_package'];
        $goodsModel->price = $data['have_package'] == 1 ? 0 : $data['price'];
        $goodsModel->install_price = $data['install_price'];

        $goodsModel->order_endtime = $data['have_package'] == 1 ? strtotime($data['order_endtime']):time();

        $goodsModel->addtime = time();
        $goodsModel->overtime = strtotime("+1year");
        $goodsModel->region_1 = $user['region_1'];
        $goodsModel->region_2 = $user['region_2'];
        $goodsModel->region_3 = $user['region_3'];
        $goodsModel->longitude = $data['longitude'];
        $goodsModel->latitude = $data['latitude'];
        $goodsModel->region_area = $data['region_area'];
        $goodsModel->address = $data['address'];
        
        
        $goodsModel->area_num = $data['area_num'];
        
        $transaction = Yii::$app->db->beginTransaction();
        try {
            if (!$goodsModel->save(false)) {
                \Yii::getLogger()->log($goodsModel->errors, \yii\log\Logger::LEVEL_ERROR);
                throw new \Exception('商品添加失败！');
            }

            //添加商品属性
            foreach($data['goods_attr'] as $goods_attr){
                $goodsAttrModel = new GoodsAttr();
                $goodsAttrModel->goods_no = $goodsNo;
                $goodsAttrModel->name = $goods_attr['name'];
                $goodsAttrModel->attr_id = $goods_attr['attr_id'];
                $goodsAttrModel->attr_val = $goods_attr['attr_val'];
                $goodsAttrModel->val = $goods_attr['val'];
                $goodsAttrModel->sort = $goods_attr['sort'];
                $goodsAttrModel->addtime = time();
                if(!$goodsAttrModel->save(false)){
                    \Yii::getLogger()->log($goodsAttrModel->errors, \yii\log\Logger::LEVEL_ERROR);
                    throw new \Exception('商品属性添加失败！');
                }
            }
            //添加商品图片
            foreach($data['goodsimg'] as $goodsimg){
                $goodsImgModel = new GoodsImg();
                $goodsImgModel->goods_no = $goodsNo;
                $goodsImgModel->src = $goodsimg;
                $goodsImgModel->addtime = time();
                if(!$goodsImgModel->save(false)){
                    \Yii::getLogger()->log($goodsImgModel->errors, \yii\log\Logger::LEVEL_ERROR);
                    throw new \Exception('商品图片添加失败！');
                }
                //$goodsimg
            }
            //添加商品套餐信息
            if($data['have_package'] == 1){
                $package_arr = explode("\n", $data['package']);
                foreach($package_arr as $package){
                    $package_info = explode(" ", $package);
                    if(count($package_info) != 4 && $data['first_cate']==1){
                        \Yii::getLogger()->log('商品套餐格式有误', \yii\log\Logger::LEVEL_ERROR);
                        throw new \Exception('商品套餐格式有误！');
                    }
                    
                    if(count($package_info) != 3 && $data['first_cate'] != 1){
                        \Yii::getLogger()->log('商品套餐格式有误', \yii\log\Logger::LEVEL_ERROR);
                        throw new \Exception('商品套餐格式有误！');
                    }
                    
                    $goodsPackModel = new GoodsPackage();
                    $goodsPackModel->goods_no = $goodsNo;
                    $goodsPackModel->name = $package_info[0];
                    $goodsPackModel->price = $package_info[1];
                    $goodsPackModel->install_price = $data['first_cate']==1 ? $package_info[2] : 0;
                    $goodsPackModel->nums = $data['first_cate']==1 ? 0 : $package_info[2];
                    $goodsPackModel->buy_able_time = $data['first_cate']==1 ? strtotime($package_info[3]) : time();
                    $goodsPackModel->addtime = time();
                    if(!$goodsPackModel->save(false)){
                        \Yii::getLogger()->log($goodsPackModel->errors, \yii\log\Logger::LEVEL_ERROR);
                        throw new \Exception('商品套餐添加失败！');
                    }
                }
            }
            //添加商品介绍
            if($data['introduction'] != ''){
                $goodsIntroduceModel = new GoodsIntroduction();
                $goodsIntroduceModel->goods_no = $goodsNo;
                $goodsIntroduceModel->introduction = $data['introduction'];
                $goodsIntroduceModel->addtime = time();
                if(!$goodsIntroduceModel->save(false)){
                        \Yii::getLogger()->log($goodsIntroduceModel->errors, \yii\log\Logger::LEVEL_ERROR);
                        throw new \Exception('商品介绍添加失败！');
                    }
            }
            $transaction->commit();
            
            return true;
        } catch (\Exception $e) {
            $transaction->rollBack();
            
            $output['success'] = 0;
            $output['msg'] = $e->getMessage();
            Tools::outputjson($output);
            
//            Yii::$app->session->setFlash('danger', $e->getMessage());
//            return false;
        }
        
    }
    
    /***
     * 商品修改数据保存
     */
    public static function goodsUpdateSave($user){
        $goodsid = Tools::GetSafeParam('goodsid', 0, 0);
        $goodsname = Tools::GetSafeParam('goodsname', "", 1);
        $area_num = Tools::GetSafeParam('area_num', 0, 0);
        $price = Tools::GetSafeParam('price', 0, 0);
        $install_price = Tools::GetSafeParam('install_price', 0, 0);
        $have_package = Tools::GetSafeParam('have_package', 0, 0);
        $package = Tools::GetSafeParam('package', '', 1);
        $is_tall = Tools::GetSafeParam('is_tall', 0, 0);
        $longitude = Tools::GetSafeParam('longitude', "0", 1);
        $latitude = Tools::GetSafeParam('latitude', "0", 1);
        $address = Tools::GetSafeParam('address', "0", 1);
        $region_area = Tools::GetSafeParam('region_area', "0", 1);
        $introduction = Tools::GetSafeParam('introduction', "", 1);
        
        $goodsModel = Goods::findOne(['id'=>$goodsid]);
        if($goodsModel->seller_id != $user['userid'])
        {
            $output['success'] = 0;
            $output['msg'] = '没有权限修改！';
            Tools::outputjson($output);
        }
        
        if($goodsname == ''){
            $output['success'] = 0;
            $output['msg'] = '请输入【商品名称】！';
            Tools::outputjson($output);
        }
        if($area_num == 0 && $goodsModel->first_cate==1){
            $output['success'] = 0;
            $output['msg'] = '请输入【广告面积】！';
            Tools::outputjson($output);
        }
        if($have_package == 0 && $price == 0){
            $output['success'] = 0;
            $output['msg'] = '请选输入【商品价格】！';
            Tools::outputjson($output);
        }
        if(!is_numeric($price)){
            $output['success'] = 0;
            $output['msg'] = '【商品价格】必须是阿拉伯数字！';
            Tools::outputjson($output);
        }
        
        if(!is_numeric($install_price) && $goodsModel->first_cate==1){
            $output['success'] = 0;
            $output['msg'] = '【安装维护费】必须是阿拉伯数字！';
            Tools::outputjson($output);
        }
        
        if($is_tall != 0 && $is_tall != 1 && $goodsModel->first_cate==1){
            $output['success'] = 0;
            $output['msg'] = '请选择【是否高空】！';
            Tools::outputjson($output);
        }
        
        
        if($have_package == 1 && $package==""){
            $output['success'] = 0;
            $output['msg'] = '请填入【套餐信息】！';
            Tools::outputjson($output);
        }
        
        if($goodsModel->first_cate != 1 && $introduction == ''){
            $output['success'] = 0;
            $output['msg'] = '请编辑【商品介绍】！';
            Tools::outputjson($output);
        }
        
        
        //商品图片数据获取：$goodsimg
        $goodsimg = [];
        $goodsimg_nums = 0;
        for($i=0;$i<6;$i++){
            $imgurl = Tools::GetSafeParam('goodsimg_'.$i, "", 1);
            if($imgurl != ""){
                $goodsimg_nums++;
                array_push($goodsimg,$imgurl);
            }
        }
        if($goodsimg_nums == 0){
            $output['success'] = 0;
            $output['msg'] = '需至少上传一张【商品图片】！';
            Tools::outputjson($output);
        }
        
        //根据类型检测商品属性是否正确，合并商品属性与属性值：$goods_attr
        $goods_attr = [];
        $cate_attr = CateAttr::getAttrlistByCate($goodsModel->third_cate);
        foreach($cate_attr as $attr){
            $input_name = 'attr_'.$attr['id'];
            
            if($attr['type']==0){
                $attr_val = Tools::GetSafeParam($input_name, '', 1);
                if($attr['is_must'] == 1 && $attr_val == ""){
                    $output['success'] = 0;
                    $output['msg'] = '请输入【'.$attr['name']."】";
                    Tools::outputjson($output);
                }
                array_push($goods_attr,['name'=>$attr['name'],'attr_id'=>$attr['id'],'attr_val'=>'','sort'=>$attr['sort'],'val'=>$attr_val]);
            }
            if($attr['type']==1){
                $attr_val = Tools::GetSafeParam($input_name, 0, 0);
                $attr_arr = CateAttrVal::getCateAttrArrByAttrId($attr['id']);
                if($attr['is_must'] == 1 && $attr_val == ""){
                    $output['success'] = 0;
                    $output['msg'] = '请选择【'.$attr['name']."】";
                    Tools::outputjson($output);
                }
                array_push($goods_attr,['name'=>$attr['name'],'attr_id'=>$attr['id'],'attr_val'=>$attr_val,'sort'=>$attr['sort'],'val'=>$attr_arr[$attr_val]]);
            }
            if($attr['type']==2){
                $attr_val_arr = [];
                $attr_val = Tools::GetSafeParam($input_name, "", 1);
                if(strlen($attr_val)>2){
                    $attr_val_arr = explode(',', $attr_val);
                }else{
                    $attr_val_arr = [$attr_val];
                }
                $attr_arr = CateAttrVal::getCateAttrArrByAttrId($attr['id']);
                $val_arr = [];
                foreach($attr_val_arr as $val){
                    array_push($val_arr,$attr_arr[$val]);
                }
                $attr_string = implode(',', $val_arr);
                if($attr['is_must'] == 1 && $attr_string == ""){
                    $output['success'] = 0;
                    $output['msg'] = '请至少选择一个【'.$attr['name']."】";
                    Tools::outputjson($output);
                }
                array_push($goods_attr,['name'=>$attr['name'],'attr_id'=>$attr['id'],'attr_val'=>$attr_val,'sort'=>$attr['sort'],'val'=>$attr_string]);
            }
        }
        
        $data = [];
        
        $data['goodsname'] = $goodsname;
        $data['price'] = $price;
        $data['install_price'] = $install_price;
        
        $data['is_tall'] = $is_tall;
        $data['have_package'] = $have_package;
        if($have_package == 1){
            $data['package'] = $package;
        }
        $data['area_num'] = $area_num;
        $data['longitude'] = $longitude;
        $data['latitude'] = $latitude;
        $data['address'] = $address;
        $data['region_area'] = $region_area;
        
        
        $data['goodsimg'] = $goodsimg;
        $data['goods_attr'] = $goods_attr;
        
        $goodsModel->name = $data['goodsname'];
        $goodsModel->price = $data['price'];
        $goodsModel->install_price = $data['install_price'];
        $goodsModel->is_tall = $data['is_tall'];
        
        $goodsModel->addtime = time();
        $goodsModel->longitude = $data['longitude'];
        $goodsModel->latitude = $data['latitude'];
        $goodsModel->address = $data['address'];
        $goodsModel->region_area = $data['region_area'];
        $goodsModel->area_num = $data['area_num'];
        $goodsModel->status = 1;//修改后直接上架
        if($goodsModel->first_cate != 1){
            $goodsModel->have_package = $data['have_package'];
        }
        
        $transaction = Yii::$app->db->beginTransaction();
        try {
            if (!$goodsModel->save(false)) {
                \Yii::getLogger()->log($goodsModel->errors, \yii\log\Logger::LEVEL_ERROR);
                throw new \Exception('商品修改失败！');
            }
            //删除原属性的记录
            //检测是否存在原属性
            $exits = GoodsAttr::findOne(['goods_no'=>$goodsModel->goods_no]);
            if(!empty($exits) && !GoodsAttr::deleteAll(['goods_no'=>$goodsModel->goods_no])){
                throw new \Exception('删除原属性信息失败！');
            }
            //添加商品属性
            foreach($data['goods_attr'] as $goods_attr){
                $goodsAttrModel = new GoodsAttr();
                $goodsAttrModel->goods_no = $goodsModel->goods_no;
                $goodsAttrModel->name = $goods_attr['name'];
                $goodsAttrModel->attr_id = $goods_attr['attr_id'];
                $goodsAttrModel->attr_val = $goods_attr['attr_val'];
                $goodsAttrModel->val = $goods_attr['val'];
                $goodsAttrModel->sort = $goods_attr['sort'];
                $goodsAttrModel->addtime = time();
                if(!$goodsAttrModel->save(false)){
                    \Yii::getLogger()->log($goodsAttrModel->errors, \yii\log\Logger::LEVEL_ERROR);
                    throw new \Exception('商品属性添加失败！');
                }
            }
            //删除原图片的记录
            $exitsimg = GoodsImg::findOne(['goods_no'=>$goodsModel->goods_no]);
            if(!empty($exitsimg) && !GoodsImg::deleteAll(['goods_no'=>$goodsModel->goods_no])){
                throw new \Exception('删除原图片信息失败！');
            }
            //添加商品图片
            foreach($data['goodsimg'] as $goodsimg){
                $goodsImgModel = new GoodsImg();
                $goodsImgModel->goods_no = $goodsModel->goods_no;;
                $goodsImgModel->src = $goodsimg;
                $goodsImgModel->addtime = time();
                if(!$goodsImgModel->save(false)){
                    \Yii::getLogger()->log($goodsImgModel->errors, \yii\log\Logger::LEVEL_ERROR);
                    throw new \Exception('商品图片添加失败！');
                }
                //$goodsimg
            }
            
            //保存新套餐的记录
            if($goodsModel->first_cate != 1){//广告位类型的商品，不能编辑套餐内容
                //删除原套餐记录
                $existpackage = GoodsPackage::findOne(['goods_no'=>$goodsModel->goods_no]);
                if(!empty($existpackage) && !GoodsPackage::deleteAll(['goods_no'=>$goodsModel->goods_no])){
                    throw new \Exception('删除原套餐信息失败！');
                }
                if($data['have_package'] == 1){
                    $package_arr = explode("\n", $data['package']);
                    foreach($package_arr as $package){
                        $package_info = explode(" ", $package);
                        if(count($package_info) != 3){
                            \Yii::getLogger()->log('非广告位商品套餐格式有误', \yii\log\Logger::LEVEL_ERROR);
                            throw new \Exception('套餐格式有误！');
                        }
                        $goodsPackModel = new GoodsPackage();
                        $goodsPackModel->goods_no = $goodsModel->goods_no;
                        $goodsPackModel->name = $package_info[0];
                        $goodsPackModel->price = $package_info[1];
                        $goodsPackModel->nums = $package_info[2];
                        $goodsPackModel->install_price = 0;
                        $goodsPackModel->buy_able_time = time();
                        $goodsPackModel->addtime = time();
                        if(!$goodsPackModel->save(false)){
                            \Yii::getLogger()->log($goodsPackModel->errors, \yii\log\Logger::LEVEL_ERROR);
                            throw new \Exception('商品套餐添加失败！');
                        }
                    }
                }
                
            }
            //商品介绍
            if($goodsModel->first_cate != 1){
                $existintroduce = GoodsIntroduction::findOne(['goods_no'=>$goodsModel->goods_no]);
                if(!empty($existintroduce) && !GoodsIntroduction::deleteAll(['goods_no'=>$goodsModel->goods_no])){
                    throw new \Exception('删除原商品介绍失败！');
                }
                $goodsIntroModel = new GoodsIntroduction();
                $goodsIntroModel->goods_no = $goodsModel->goods_no;
                $goodsIntroModel->introduction = $introduction;
                $goodsIntroModel->addtime = time();
                if(!$goodsIntroModel->save(false)){
                    \Yii::getLogger()->log($goodsIntroModel->errors, \yii\log\Logger::LEVEL_ERROR);
                    throw new \Exception('商品介绍添加失败！');
                }
            }
            
            $transaction->commit();
            
            return true;
        } catch (\Exception $e) {
            $transaction->rollBack();
            $output['success'] = 0;
            $output['msg'] = $e->getMessage();
            Tools::outputjson($output);
            
//            Yii::$app->session->setFlash('danger', $e->getMessage());
//            return false;
        }
    }
    
    /**
     * 获取首页的商品数据
     */
    public static function getIndexpageGoods(){
        $data = Category::getIndexpageCate();        
        foreach($data as $first_key=>$first_cate){
            $sub = Category::getSubCate($first_cate['id']);
            foreach ($sub as $second_key=>$second_cate){
                //获取商品数据
                $goods = self::getGoodsBySecondCate($second_cate['id']);
                foreach ($goods as $goods_key=>$goods_val){
                    //获取商品图片
                    $goods[$goods_key]['img'] = GoodsImg::getDefaultGoodsimgByGoodsno($goods_val['goods_no']);
                }
                
                $sub[$second_key]['goods'] = $goods;
            }
            $data[$first_key]['sub'] = $sub;
        }
        return $data;
    }
    
    public static function getGoodsBySecondCate($cate_id) {
        $sql = "select id,name,price,goods_no from goods where second_cate=$cate_id and status=1 order by sort desc limit 0,6";
        $command = \Yii::$app->db->createCommand($sql);
    	return $model = $command->queryAll();
    }
    
    public static function getGoodsList($condition,$page_no){
        //获取符合条件的商品的个数
        $perpage = 15;
        $sql_condition_arr = [];
        array_push($sql_condition_arr,'status!=4');
        if($condition['second_cate'] != 0){
            array_push($sql_condition_arr,'second_cate='.$condition['second_cate']);
        }
        
        if($condition['third_cate'] != 0){
            array_push($sql_condition_arr,'third_cate='.$condition['third_cate']);
        }
        
        $data['third_cate_arr'] = Category::getSubCate($condition['second_cate']);
        
        $sql_condition_string = implode(' and ', $sql_condition_arr);
        $data['total'] = self::getCountByCondition($sql_condition_string);
        $begin = $perpage*($page_no-1);
        $goodsdata = self::getGoodsByPage($sql_condition_string, $begin, $perpage);
        foreach($goodsdata as $key=>$value){
            $goodsdata[$key]['img'] = GoodsImg::getDefaultGoodsimgByGoodsno($value['goods_no']);
            $goodsdata[$key]['addtime'] = date('Y-m-d H:i:s',$value['addtime']);
        }
        $data['goodsdata'] = $goodsdata;
        $data['pagenums'] = ceil($data['total']/$perpage);
        $data['page_no'] = $page_no;
        $data['perpage'] = $perpage;
        $data['second_cate'] = $condition['second_cate'];
        $data['third_cate'] = $condition['third_cate'];
        return $data;
    }
    
    public static function getBackendGoodsList($condition,$page_no){
        //获取符合条件的商品的个数
        
        $perpage = 15;
        $sql_condition_arr = [];
        array_push($sql_condition_arr,'status!=4');//过滤掉被删除的商品
        if(isset($condition['name']) && $condition['name'] !== ""){
            array_push($sql_condition_arr,"name='".$condition['name']."'");
        }
        if(isset($condition['seller']) && $condition['seller'] !== ""){
            array_push($sql_condition_arr,"seller='".$condition['seller']."'");
        }
        if(isset($condition['status']) && $condition['status'] !== ""){
            array_push($sql_condition_arr,"status=".$condition['status']."");
        }
        if(isset($condition['seller_id']) && $condition['seller_id'] !== ""){
            array_push($sql_condition_arr,"seller_id=".$condition['seller_id']);
        }
        if(isset($condition['region_3']) && $condition['region_3'] != 0){
            array_push($sql_condition_arr,'region_3='.$condition['region_3']);
        }
        if(isset($condition['first_cate']) && $condition['first_cate'] != 0){
            array_push($sql_condition_arr,'first_cate='.$condition['first_cate']);
        }
        if(isset($condition['second_cate']) && $condition['second_cate'] != 0){
            array_push($sql_condition_arr,'second_cate='.$condition['second_cate']);
        }
        if(isset($condition['third_cate']) && $condition['third_cate'] != 0){
            array_push($sql_condition_arr,'third_cate='.$condition['third_cate']);
        }
        
        $sql_condition_string = implode(' and ', $sql_condition_arr);
        $data['total'] = self::getCountByCondition($sql_condition_string);
        $begin = $perpage*($page_no-1);
        $goodsdata = self::getGoodsByPage($sql_condition_string, $begin, $perpage);
        foreach($goodsdata as $key=>$value){
            $goodsdata[$key]['img'] = GoodsImg::getDefaultGoodsimgByGoodsno($value['goods_no']);
            $goodsdata[$key]['addtime'] = date('Y-m-d H:i:s',$value['addtime']);
        }
        $data['goodsdata'] = $goodsdata;
        $data['pagenums'] = ceil($data['total']/$perpage);
        $data['page_no'] = $page_no;
        $data['perpage'] = $perpage;
        return $data;
    }
    
    public static function getCountByCondition($sql_condition_string){
        $sql = "select count(id) total from goods where $sql_condition_string";
        $command = \Yii::$app->db->createCommand($sql);
    	$model = $command->queryOne();
        return $model['total'];
    }
    
    public static function getGoodsByPage($sql_condition_string,$begin,$perpage){
        $sql = "select id,goods_no,name,price,status,seller,seller_id,first_cate,second_cate,third_cate,order_endtime,addtime from goods where $sql_condition_string order by id desc, sort desc limit $begin,$perpage";
        $command = \Yii::$app->db->createCommand($sql);
    	return $model = $command->queryAll();
    }
    
    public static function getGoodsByGoodsid($goods_id){
        $sql = "select * from goods where id = $goods_id";
        $command = \Yii::$app->db->createCommand($sql);
    	return $model = $command->queryOne();
    }
    
    public static function getGoodsDetail($goods_id){
        $data = self::getGoodsByGoodsid($goods_id);
        $data['attrs'] = GoodsAttr::getAttrByGoodsno($data['goods_no']);
        $data['imgs'] = GoodsImg::getDetailImgsByGoodsno($data['goods_no']);
        $data['packages'] = GoodsPackage::getPackageByGoodsno($data['goods_no']);
        return $data;
    }
    
    //获取道闸广告位商品集合
    public static function getDaozhaGoods($seller_id){
        $sql = "select * from goods where seller_id=$seller_id and have_package=1 and status=1 and first_cate=1";
        $command = \Yii::$app->db->createCommand($sql);
        $models = $command->queryAll();
        foreach($models as $key=>$value){
            $models[$key]['packages'] = GoodsPackage::getPackageByGoodsno($value['goods_no']);
            $models[$key]['img'] = GoodsImg::getDefaultGoodsimgByGoodsno($value['goods_no']);
        }
        return $models;
    }
    
    public static function getGoodslistBySellerId($sellerid){
        $page_no = Tools::GetSafeParam('page_no', 1, 0);
        //获取符合条件的商品的个数
        $perpage = 10;
        $sql_condition_string = "seller_id=$sellerid and status!=4";
        $data['total'] = self::getCountByCondition($sql_condition_string);
        $begin = $perpage*($page_no-1);
        $goodsdata = self::getGoodsByPage($sql_condition_string, $begin, $perpage);
        foreach($goodsdata as $key=>$value){
            $goodsdata[$key]['img'] = GoodsImg::getDefaultGoodsimgByGoodsno($value['goods_no']);
        }
        $data['goodsdata'] = $goodsdata;
        $data['pagenums'] = ceil($data['total']/$perpage);
        $data['page_no'] = $page_no;
        $data['perpage'] = $perpage;
        return $data;
    }
}
